// import http from "wechat-http"
// console.log(http)
// http.baseURL = "https://live-api.itheima.net"
// wx.http = http;
// export default http
import http from "wechat-http"
http.baseURL = "https://live-api.itheima.net"
http.intercept.request = (params) => {
	const {
		token
	} = getApp();
	const defaultheader = {};
	if (token) defaultheader.Authorization = token
	params.header = Object.assign(defaultheader, params.header)
	return params
}
http.intercept.response = async ({
	statusCode,
	data,
	config
}) => {
	if (statusCode === 401) {
		if (config.url.includes("/refreshToken")) {
			const pageStack = getCurrentPages();
			const lastPage = pageStack[pageStack.length - 1];
			const redirectUrl = lastPage.route
			return wx.redirectTo({
				url: `/pages/login/login?redirecturl=${redirectUrl}`,
			})
		}
		const app = getApp()
		console.log(app)
		const res = await http({
			url: "/refreshToken",
			method: "post",
			header: {
				Authorization: app.refreshToken
			}
		})
		console.log(res)

		wx.setStorageSync("token", 'Bearer ' + res.data.token);
		app.token = 'Bearer ' + res.data.token
		app.refreshToken = 'Bearer ' + res.data.refreshToken
		wx.setStorageSync('refreshToken', 'Bearer ' + res.data.refreshToken)
		return http(
			Object.assign(config, {
				header: {
					Authorization: app.token
				}
			})
		)
	}
	return data
}
wx.http = http;
export default http;